import { HTTP_REQUEST_URL, HEADER, TOKENNAME } from "@/config/app";
import { toLogin, checkLogin } from "../libs/login.js";
import { editSign } from "./reqestSign.js";
import util from "./util";
import store from "../store/index.js";
import { authParams } from "./auth.js";

function baseRequest(url, method, data, { noAuth = true, noVerify = false }) {
  let Url = HTTP_REQUEST_URL,
    header = {
      "content-type": "application/json",
    };
  let signObj = {};
  // #ifdef H5
  let token = store.state.app.token;
  // #endif
  // #ifdef MP
  let token = store.state.app.token_wx;
  // #endif

  if (!noAuth) {
    //登录过期自动登录
    if (!store.state.app.token && !checkLogin()) {
      store.commit("LOGOUT");
      util.Tips(
        {
          title: "登录已过期，请重新登录！",
        },
        () => {
          uni.navigateTo({
            url: "/pagesWater/users/login",
          });
        }
      );
    }
  }
  if (token) header[TOKENNAME] = token;
  let JSONData = method == "post" || method == "put" ? data : data?.params;

  //去掉多余 报错参数
  let authData = authParams(JSONData || {});

  if (method == "get" || method == "put") {
    signObj = editSign(authData);
  }
  if (method == "post" || method == "delete") {
    
    signObj = editSign(authData);
  }
  return new Promise((reslove, reject) => {
    uni.request({
      url: Url + url,
      method: method || "GET",
      header: {
        ...header,
        ...signObj,
      },
      data: authData || {},
      success: (res) => {
        if (noVerify) reslove(res.data, res);
        else if (res.data.code == 200) reslove(res.data);
        else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
          util.Tips(
            {
              title: res.data.message,
            },
            () => {
              uni.navigateTo({
                url: "/pagesWater/users/login",
              });
            }
          );
          reject(res.data);
        } else if (res.data.code == 402) {
          util.Tips(res.data.message);
          reject(res.message);
        } else if (res.data.code == 403) {
          reslove(res.data);
          util.Tips(res.data.message || "网络繁忙");
        } else if (res.data.code == 5000) {
          //税务登录重新登录
          reslove(res.data);
        } else if (res.data.code == 5100) {
          //税务登录uuid过期
          reslove(res.data);
        } else {
          util.Tips(res.data?.message || res.data?.error || "网络繁忙");
          reject(res.data);
        }
      },
      fail: (msg) => {
        reject("请求失败");
      },
      complete: () => {
        header = {
          "content-type": "application/json",
        }; //很奇怪 每次请求完为什么 都要重置这个请求头 不重置 就会有 很诡异的bug
      },
    });
  });
}

const request = {};

["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  (method) => {
    request[method] = (api, data, opt, params) =>
      baseRequest(api, method, data, opt || {}, params);
  }
);

export default request;
